﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Security;
using System.Security.Principal;
using System.Web.Security;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Web;
using XQ.Model;
using Newtonsoft.Json;

namespace XQ.Common
{
    public class Images
    {
        #region  生成验证码图片
        public byte[] CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 12);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(Color.White);
            g.Clear(Color.Blue);
            g.DrawString(checkCode, f, b, 3, 3);
            Pen blackPen = new Pen(Color.Black, 0);
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                int x1 = rand.Next(image.Width);
                int x2 = rand.Next(image.Width);
                int y1 = rand.Next(image.Height);
                int y2 = rand.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver, 1), x1, y1, x2, y2);
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="codeCount"></param>
        /// <returns></returns>
        public string CreateRandomCode(int codeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }
        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 16.0), 27);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 13, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        #endregion

        #region 返回存储地址
        /// <summary>
        /// 返回存储地址
        /// </summary>
        /// <returns></returns>
        public string GetPath(string path = "")
        {
            string savePath = "/Resource/UploadFiles/";
            if (string.IsNullOrWhiteSpace(path))
            {
                DateTime dt = DateTime.Now;
                savePath += dt.Year + "/" + dt.Month + "/" + dt.Day + "/" + dt.Hour + "/" + dt.Minute + "/";
            }
            else
            {
                savePath += path;
            }
            if (!System.IO.Directory.Exists(savePath))
            {
                System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~" + savePath));
            }
            return savePath;
        }
        /// <summary>
        /// 返回临时文件存储地址
        /// </summary>
        /// <returns></returns>
        public string GetTempPath()
        {
            string savePath = "/Resource/UploadFiles/Temp/";
            if (!System.IO.Directory.Exists(savePath))
            {
                System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~" + savePath));
            }
            return savePath;
        }
        #endregion

        #region 生成缩略图
        /// 〈summary> 
        /// 生成缩略图 
        /// 〈/summary> 
        /// 〈param name="originalImagePath">源图路径（物理路径）〈/param> 
        /// 〈param name="thumbnailPath">缩略图路径（物理路径）〈/param> 
        /// 〈param name="width">缩略图宽度〈/param> 
        /// 〈param name="height">缩略图高度〈/param> 
        /// 〈param name="mode">生成缩略图的方式〈/param>     
        public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            try
            {

                using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath))
                {
                    if (width >= originalImage.Width & height >= originalImage.Height)
                    {
                        if (File.Exists(originalImagePath))
                        {
                            string fileName = Path.GetFileNameWithoutExtension(thumbnailPath);
                            File.Move(thumbnailPath, thumbnailPath.Replace(fileName, fileName + "_1"));

                            File.Copy(originalImagePath, thumbnailPath, true);
                            return;
                        }
                    }

                    if (mode != "Cut")
                    {
                        double d1 = double.Parse(width.ToString()) / double.Parse(height.ToString());

                        //宽高比 
                        double wd = double.Parse(originalImage.Width.ToString()) / double.Parse(originalImage.Height.ToString());
                        //高宽比 
                        double hd = double.Parse(originalImage.Height.ToString()) / double.Parse(originalImage.Width.ToString());

                        double itsw = 0d;
                        double itsh = 0d;
                        //int itsin = 0;

                        //与宽高比对比 
                        if (d1 > wd)
                        {
                            itsw = d1 - wd;
                        }
                        else
                        {
                            itsw = wd - d1;
                        }

                        //与高宽比对比 
                        if (d1 > hd)
                        {
                            itsh = d1 - hd;
                        }
                        else
                        {
                            itsh = hd - d1;
                        }

                        //如果高宽比更接近比例 
                        if (itsw > itsh)
                        {
                            mode = "W";
                        }
                        else
                        {
                            mode = "H";
                        }
                    }


                    int towidth = width;
                    int toheight = height;

                    int x = 0;
                    int y = 0;
                    int ow = originalImage.Width;
                    int oh = originalImage.Height;

                    switch (mode)
                    {
                        case "HW"://指定高宽缩放（可能变形）
                            break;
                        case "W"://指定宽，高按比例
                            toheight = originalImage.Height * width / originalImage.Width;
                            break;
                        case "H"://指定高，宽按比例 
                            towidth = originalImage.Width * height / originalImage.Height;
                            break;
                        case "Cut"://指定高宽裁减（不变形）
                            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                            {
                                oh = originalImage.Height;
                                ow = originalImage.Height * towidth / toheight;
                                y = 0;
                                x = (originalImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = originalImage.Width;
                                oh = originalImage.Width * height / towidth;
                                x = 0;
                                y = (originalImage.Height - oh) / 2;
                            }
                            break;
                        default:
                            break;
                    }

                    #region 自添代码
                    if (ow <= towidth)
                    {
                        towidth = ow;
                    }
                    if (oh <= toheight)
                    {
                        toheight = oh;
                    }
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('" + ow+" "+towidth+"   "+oh+" "+toheight + "')</script>");
                    #endregion

                    //新建一个bmp图片 
                    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                    //新建一个画板 
                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                    //设置高质量插值法 
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //设置高质量,低速度呈现平滑程度 
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    ////清空画布并以透明背景色填充 
                    //g.Clear(System.Drawing.Color.Transparent);

                    //清空画布并以白色填充 
                    g.Clear(System.Drawing.Color.White);

                    //在指定位置并且按指定大小绘制原图片的指定部分 
                    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

                    //g.DrawString("58xiao.com", new Font("宋体", 14f, FontStyle.Bold), new SolidBrush(Color.White), towidth - 200, toheight - 100);
                    try
                    {
                        if (File.Exists(thumbnailPath))
                        {
                            string fileName = Path.GetFileNameWithoutExtension(thumbnailPath);
                            File.Move(thumbnailPath, thumbnailPath.Replace(fileName, fileName + "_1"));
                        }
                        //以jpg格式保存缩略图 
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    catch (System.Exception e)
                    {
                        // 强制保存一张
                        File.Copy(originalImagePath, thumbnailPath, true);

                        HttpContext.Current.Response.Write(e.ToString() + thumbnailPath);
                    }
                    finally
                    {
                        originalImage.Dispose();
                        bitmap.Dispose();
                        g.Dispose();
                    }
                }
            }
            catch
            {

            }
        }

        #endregion


        #region 生成缩略图
        /// 〈summary> 
        /// 在图片上绘制图片 
        /// 〈/summary> 
        /// 〈param name="originalImagePath">源图路径（物理路径）〈/param> 
        /// 〈param name="thumbnailPath">缩略图路径（物理路径）〈/param> 
        /// 〈param name="width">缩略图宽度〈/param> 
        /// 〈param name="height">缩略图高度〈/param> 
        /// 〈param name="mode">生成缩略图的方式〈/param>     
        public void MakeImagesToImage(string originalImagePath, string thumbnailPath, int width, int height, string mode, string jsonStr, int page, string icon)
        {
            try
            {

                using (System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath))
                {
                    //if (width >= originalImage.Width & height >= originalImage.Height)
                    //{
                    //    if (File.Exists(originalImagePath))
                    //    {
                    //        File.Copy(originalImagePath, thumbnailPath, true);
                    //        return;
                    //    }
                    //}

                    if (mode != "Cut")
                    {
                        double d1 = double.Parse(width.ToString()) / double.Parse(height.ToString());

                        //宽高比 
                        double wd = double.Parse(originalImage.Width.ToString()) / double.Parse(originalImage.Height.ToString());
                        //高宽比 
                        double hd = double.Parse(originalImage.Height.ToString()) / double.Parse(originalImage.Width.ToString());

                        double itsw = 0d;
                        double itsh = 0d;
                        //int itsin = 0;

                        //与宽高比对比 
                        if (d1 > wd)
                        {
                            itsw = d1 - wd;
                        }
                        else
                        {
                            itsw = wd - d1;
                        }

                        //与高宽比对比 
                        if (d1 > hd)
                        {
                            itsh = d1 - hd;
                        }
                        else
                        {
                            itsh = hd - d1;
                        }

                        //如果高宽比更接近比例 
                        if (itsw > itsh)
                        {
                            mode = "W";
                        }
                        else
                        {
                            mode = "H";
                        }
                    }


                    int towidth = width;
                    int toheight = height;

                    int x = 0;
                    int y = 0;
                    int ow = originalImage.Width;
                    int oh = originalImage.Height;

                    switch (mode)
                    {
                        case "HW"://指定高宽缩放（可能变形）
                            break;
                        case "W"://指定宽，高按比例
                            toheight = originalImage.Height * width / originalImage.Width;
                            break;
                        case "H"://指定高，宽按比例 
                            towidth = originalImage.Width * height / originalImage.Height;
                            break;
                        case "Cut"://指定高宽裁减（不变形）
                            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                            {
                                oh = originalImage.Height;
                                ow = originalImage.Height * towidth / toheight;
                                y = 0;
                                x = (originalImage.Width - ow) / 2;
                            }
                            else
                            {
                                ow = originalImage.Width;
                                oh = originalImage.Width * height / towidth;
                                x = 0;
                                y = (originalImage.Height - oh) / 2;
                            }
                            break;
                        default:
                            break;
                    }

                    #region 自添代码
                    if (ow <= towidth)
                    {
                        towidth = ow;
                    }
                    if (oh <= toheight)
                    {
                        toheight = oh;
                    }
                    //System.Web.HttpContext.Current.Response.Write("<script>alert('" + ow+" "+towidth+"   "+oh+" "+toheight + "')</script>");
                    #endregion

                    //新建一个bmp图片 
                    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                    //新建一个画板 
                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

                    //设置高质量插值法 
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                    //设置高质量,低速度呈现平滑程度 
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    ////清空画布并以透明背景色填充 
                    //g.Clear(System.Drawing.Color.Transparent);

                    //清空画布并以白色填充 
                    g.Clear(System.Drawing.Color.White);

                    //在指定位置并且按指定大小绘制原图片的指定部分 
                    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);
                    //g.DrawImage(Image.FromFile(@"F:\DianZiBaiBan\Web\XiaoQu\XiaoQu\resources\XQW\images\right.png"), 10, 10);

                    HWmodel user = (HWmodel)JsonConvert.DeserializeObject(jsonStr, typeof(HWmodel));
                    foreach (HWxyModel m in user.data)
                    {
                        try
                        {
                            if (m.page == page.ToString())
                            {
                                g.DrawImage(Image.FromFile(icon), (int)(towidth * decimal.Parse(m.x)), (int)(toheight * decimal.Parse(m.y)));
                            }
                        }
                        catch { }
                        //int t = user.data.Count;
                    }

                    //g.DrawString("58xiao.com", new Font("宋体", 14f, FontStyle.Bold), new SolidBrush(Color.White), towidth - 200, toheight - 100);
                    try
                    {
                        //以jpg格式保存缩略图 
                        bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                    catch (System.Exception e)
                    {

                        HttpContext.Current.Response.Write(e.ToString() + thumbnailPath);
                    }
                    finally
                    {
                        originalImage.Dispose();
                        bitmap.Dispose();
                        g.Dispose();
                    }
                }
            }
            catch
            {

            }
        }

        #endregion
    }
}
